package mweb

import (
	"fmt"
	"gitee.com/dennis-mxx/gcode-common/mcontext"
	"gitee.com/dennis-mxx/gcode-common/mlogger"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/sessions"
	"net/http"
)

type RequestContext struct {
	Stx     SessionCtx
	Ctx     *gin.Context
	Mtx     *mcontext.MContext
	session *sessions.Session
	Request *http.Request
}

func (ew RequestContext) BindJSON(obj any) error {
	return ew.Ctx.BindJSON(obj)
}
func (ew RequestContext) BindHeader(obj any) error {
	return ew.Ctx.BindHeader(obj)
}
func (ew RequestContext) BindQuery(obj any) error {
	return ew.Ctx.BindQuery(obj)
}
func (ew RequestContext) BindTOML(obj any) error {
	return ew.Ctx.BindTOML(obj)
}
func (ew RequestContext) BindUri(obj any) error {
	return ew.Ctx.BindUri(obj)
}

func (ew RequestContext) Bind(obj any) error {
	return ew.Ctx.Bind(obj)
}

func (ew RequestContext) ShouldBindJSON(obj any) error {
	return ew.Ctx.ShouldBindJSON(obj)
}

func (ew RequestContext) ShouldBindQuery(obj any) error {
	return ew.Ctx.ShouldBindQuery(obj)
}

func (ew RequestContext) ShouldBindHeader(obj any) error {
	return ew.Ctx.ShouldBindHeader(obj)
}

func (ew RequestContext) ShouldBindUri(obj any) error {
	return ew.Ctx.ShouldBindUri(obj)
}

func (ew RequestContext) Logger() *mlogger.TraceLogger {
	return ew.Mtx.Logger()
}

func (ew RequestContext) GetSession() *sessions.Session {
	if ew.session != nil {
		return ew.session
	}
	session, _ := ew.Stx.GetSession()
	return session
}
func (ew RequestContext) GetSessionValue(sessionName string) string {
	session := ew.GetSession()
	sessionValue := session.Values[sessionName]
	if sessionValue == nil {
		return ""
	} else {
		return fmt.Sprintf("%v", sessionValue)
	}
}
func (ew RequestContext) SetSessionValue(sessionName, sessionValue string) {
	session := ew.GetSession()
	session.Values[sessionName] = sessionValue
}
func (ew RequestContext) DelSession(sessionName string) {
	session := ew.GetSession()
	delete(session.Values, sessionName)
}

func (ew RequestContext) SaveSession() {
	ew.Stx.Save()
}
func (ew RequestContext) GetPara(paraName string) string {
	v, _ := ew.Ctx.Get(paraName)
	if v == nil {
		return ""
	}
	return fmt.Sprintf("%v", v)
}
func (ew RequestContext) GetParaValue(paraName string) any {
	v, _ := ew.Ctx.Get(paraName)
	return v
}
func (ew RequestContext) SetPara(paraName string, paraValue any) {
	ew.Ctx.Set(paraName, paraValue)
}

func (ew RequestContext) AbortWithStatusJSON(code int, jsonObj any) {
	ew.Ctx.AbortWithStatusJSON(code, jsonObj)
}
